package pa165.dominatingspecies.dao.common;

import javax.persistence.EntityManager;

import pa165.dominating.species.dao.PersistObject;
import pa165.dominating.species.exceptions.DataStorageException;
import pa165.dominating.species.exceptions.EntityException;

/**
 * @author Tomas Kalla
 */
public class Validator {

    private static final String NULL_ENTITY_MSG = "Entity cannot be null";

    //-----------------------------------------------------------
    /**
     * Validates new entity.
     *
     * @param entity to be validated
     */
    public static void validateNewEntity(final PersistObject entity) {
        if (entity == null) {
            throw new EntityException(NULL_ENTITY_MSG); // exceptions thrown by dao should be DataAccessException or subclass
        }

        if (entity.getId() != null) {
            throw new EntityException("New entity cannot have assigned id.");
        }
    }

    /**
     * Validates entity for update.
     *
     * @param entity entity for update
     */
    public static void validateUpdatedEntity(final PersistObject entity) {
        if (entity == null) {
            throw new EntityException(NULL_ENTITY_MSG);
        }

        if (entity.getId() == null) {
            throw new EntityException("Existing entity must have assigned ID.");
        }

    }

    public static void validateEntityManager(final EntityManager entityManager) {
        if (entityManager == null) {
            throw new DataStorageException("Entity manager is not set.");
        }
    }

    public static void validateDeleteEntity(final PersistObject entity) {
        if (entity == null) {
            throw new EntityException(NULL_ENTITY_MSG);
        }
        if (entity.getId() == null) {
            throw new EntityException("ID must not be null if object is to be deleted.");
        }
    }

    public static void validateGetEntity(final Long id) {
        if (id == null) {
            throw new EntityException("ID to be looked up cannot be null");
        }
    }
}
